extends Node2D

@export var damage = 10
@export var attack_cooldown = 0.8  # 攻击冷却时间（秒）
@export var search_radius = 400.0  # 搜索半径
@export var chain_count = 3  # 闪电可以跳跃的敌人数量
@export var chain_range = 150.0  # 闪电跳跃范围
@export var chain_damage_reduction = 0.8  # 每次跳跃后的伤害衰减（乘数）

@onready var attack_timer = $AttackTimer
@onready var animation_player = $AnimationPlayer

var owner_player = null  # 持有此武器的玩家引用
var hit_enemies = []  # 已经被当前闪电链击中的敌人

func _ready():
	attack_timer.wait_time = attack_cooldown
	attack_timer.one_shot = false  # 设置为重复
	attack_timer.start()
	
	# 确保有动画播放器
	if not animation_player:
		print("WARNING: LightningChain missing AnimationPlayer!")

func set_owner_player(player_node):
	owner_player = player_node

func _on_attack_timer_timeout():
	find_and_attack_enemy()

func find_and_attack_enemy():
	var closest_enemy = null
	var min_distance_sq = search_radius * search_radius  # 使用平方距离提高效率
	
	# 获取场景树中"enemies"组内的所有敌人
	var enemies = get_tree().get_nodes_in_group("enemies")
	
	for enemy in enemies:
		# 确保敌人有效且未被标记为删除
		if is_instance_valid(enemy) and enemy.has_method("take_damage"):
			var distance_sq = global_position.distance_squared_to(enemy.global_position)
			if distance_sq < min_distance_sq:
				min_distance_sq = distance_sq
				closest_enemy = enemy
	
	if closest_enemy:
		hit_enemies.clear()  # 清空已击中敌人列表
		attack(closest_enemy, damage)  # 从第一个敌人开始闪电链

func attack(target_enemy, current_damage):
	# 将目标添加到已击中列表
	hit_enemies.append(target_enemy)
	
	# 应用暴击（如果玩家有暴击属性）
	var actual_damage = current_damage
	var is_crit = false
	
	if owner_player and owner_player.has_method("get_crit_info") and hit_enemies.size() == 1:
		var crit_info = owner_player.get_crit_info()
		if randf() < crit_info.chance:
			actual_damage *= crit_info.multiplier
			is_crit = true
	
	# 对目标造成伤害
	target_enemy.take_damage(actual_damage)
	
	# 创建闪电效果
	create_lightning_effect(global_position, target_enemy.global_position, is_crit)
	
	print(name, " 闪电攻击 ", target_enemy.name, " 造成 ", actual_damage, " 伤害")
	
	# 如果还可以继续跳跃，寻找下一个目标
	if hit_enemies.size() < chain_count:
		var next_target = find_next_chain_target(target_enemy.global_position)
		if next_target:
			# 计算下一次伤害（衰减）
			var next_damage = current_damage * chain_damage_reduction
			# 递归调用，攻击下一个目标
			attack(next_target, next_damage)

func find_next_chain_target(current_position):
	var closest_enemy = null
	var min_distance_sq = chain_range * chain_range
	
	# 获取场景树中"enemies"组内的所有敌人
	var enemies = get_tree().get_nodes_in_group("enemies")
	
	for enemy in enemies:
		# 确保敌人有效、未被标记为删除、尚未被击中
		if is_instance_valid(enemy) and enemy.has_method("take_damage") and not hit_enemies.has(enemy):
			var distance_sq = current_position.distance_squared_to(enemy.global_position)
			if distance_sq < min_distance_sq:
				min_distance_sq = distance_sq
				closest_enemy = enemy
	
	return closest_enemy

func create_lightning_effect(start_pos, end_pos, is_critical):
	# 创建闪电视觉效果
	var lightning = preload("res://LightningEffect.tscn").instantiate()
	get_tree().get_root().add_child(lightning)
	
	# 设置闪电属性
	lightning.start_point = start_pos
	lightning.end_point = end_pos
	lightning.is_critical = is_critical
	
	# 播放攻击动画（如果有）
	if animation_player and animation_player.has_animation("attack"):
		animation_player.play("attack")

# 由Player的apply_upgrade函数调用
func upgrade_stat(stat_name, value):
	match stat_name:
		"damage":
			damage += value
			print(name, " 伤害提升至: ", damage)
		"speed":  # 减少冷却时间
			attack_cooldown = max(0.1, attack_cooldown - value)  # 确保冷却时间不低于最小值
			attack_timer.wait_time = attack_cooldown
			print(name, " 攻击冷却减少至: ", attack_cooldown)
		"range":  # 增加搜索范围
			search_radius += value
			print(name, " 搜索范围增加至: ", search_radius)
		"chain":  # 增加闪电链数量
			chain_count += value
			print(name, " 闪电链数量增加至: ", chain_count)
		"chain_range":  # 增加闪电跳跃范围
			chain_range += value
			print(name, " 闪电跳跃范围增加至: ", chain_range)
		_:
			print("未知属性升级: ", stat_name)
